﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SportsPlatform.Application.Dto.SportBusiness.CompetitionProjec;
using SportsPlatform.Application.Query.CompetitionProjec;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.CompetitionProjec;
using SportsPlatform.Enums;
using SportsPlatform.Global;
using SportsPlatform.Helpers;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.CompetitionProjec;
using SportsPlatform.SportBusiness.ISportBusiness;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 赛事项目相关实现类
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class CompetitionProjectService : SportsPlatformAppServiceBase, ICompetitionProjectService
    {
        #region 私有类型

        private readonly IRepository<CompetitionProject, Guid> repository;
        private readonly IRepository<Competition, Guid> comRepository;
        private readonly IRepository<CompetitionRuleInfo, Guid> ruleRepository;
        private readonly IRepository<Project, Guid> projectRepository;
        private readonly IRepository<ProjectType, Guid> typeRepository;
        private readonly IRepository<RuleApplyProject, Guid> rapRepository;
        private readonly IRepository<RegistrationInfo, Guid> regRepository;
        private readonly IRepository<CompeteTeam, Guid> comteamRepository;
        private readonly IRepository<Employee, Guid> employeeRepository;


        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        public CompetitionProjectService(IRepository<CompetitionProject, Guid> _repository,
            IRepository<Competition, Guid> _comRepository,
            IRepository<CompetitionRuleInfo, Guid> _ruleRepository,
            IRepository<Project, Guid> _projectRepository,
            IRepository<ProjectType, Guid> _typeRepository,
            IRepository<RuleApplyProject, Guid> _rapReponsitory,
            IRepository<RegistrationInfo, Guid> _regReponsitory,
            IRepository<Employee, Guid> _employeeRepository,
            IRepository<CompeteTeam, Guid> _comteamRepository, IHttpContextAccessor context) : base(context)
        {
            repository = _repository;
            comRepository = _comRepository;
            ruleRepository = _ruleRepository;
            projectRepository = _projectRepository;
            typeRepository = _typeRepository;
            rapRepository = _rapReponsitory;
            regRepository = _regReponsitory;
            comteamRepository = _comteamRepository;
            employeeRepository = _employeeRepository;
        }

        #endregion

        #region 公共API接口方法

        /// <summary>
        /// 获取赛事比赛项目列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetCompetitionProjecListDto>> GetCompetitionProjecList(GetCompetitionProjecListQuery query)
        {
            var res = new PagePagingDto<GetCompetitionProjecListDto>() { IsSuccess = true, Data = null, TotalCount = 0, TotalPage = 0, Code = HttpResultCode.NotData };
            var list = new List<GetCompetitionProjecListDto>();
            var comproject = await repository.GetAllListAsync();
            var result = comproject.Where(a => a.CompetitionId == query.CompetitionId)
                .WhereIF(query.State != null && query.State > -1, a => a.State == query.State)
                .Where(a => a.IsDeleted == false)
                .WhereIF(!string.IsNullOrWhiteSpace(query.KeyWord), a => a.Name.Contains(query.KeyWord))
                .OrderByDescending(a => a.CreateTime)
                .Skip(query.PageSize * (query.PageIndex - 1))
                .Take(query.PageSize)
                .ToList();

            var count = comproject.Where(a => a.CompetitionId == query.CompetitionId)
                .WhereIF(query.State != null && query.State > -1, a => a.State == query.State)
                .Where(a => a.IsDeleted == false)
                .WhereIF(!string.IsNullOrWhiteSpace(query.KeyWord), a => a.Name.Contains(query.KeyWord))
                .OrderByDescending(a => a.CreateTime)
                .ToList().Count;
            var com = await comRepository.GetAsync(query.CompetitionId);
            if (result.Count > 0)
            {
                var reglist = await regRepository.GetAllListAsync(info => info.IsDeleted == false && info.CompetitionId == query.CompetitionId && info.RegistrationStatus == (int)RegistrationStatusEnum.报名成功);
                var rulelist = await ruleRepository.GetAllListAsync();
                var projectlist = await projectRepository.GetAllListAsync();
                var projecttypelist = await typeRepository.GetAllListAsync();

                foreach (var item in result)
                {
                    var p = new GetCompetitionProjecListDto();
                    p.Id = item.Id;
                    p.Address = item.Address + " | " + item.Stadium;
                    p.GameType = item.GameType;
                    p.GameTypeName = Enum.GetName(typeof(CompetitionProjectTypeEnum), item.GameType);
                    var gameendtime = item.GameBeginTime.Date == item.GameEndTime.Date ? item.GameEndTime.ToString("HH:mm") : item.GameEndTime.ToString("yyyy-MM-dd HH:mm");
                    p.GameDate = $"{item.GameBeginTime.ToString("yyyy-MM-dd HH:mm")}～{gameendtime}";
                    p.SensorsMaxNum = item.SensorsMaxNum;
                    p.TeamMaxUserNum = item.TeamMaxUserNum;
                    p.UserNum = reglist.Where(info => info.CompetitionProjectId == item.Id).ToList().Count;
                    p.MaxEmployeeNum = item.MaxEmployeeNum;
                    p.Name = item.Name;
                    p.CompetitionId = com.Id;
                    p.CompetitionName = com.Name;
                    p.State = item.State;
                    p.Money = item.IsFree == true ? "0" : item.CostMoney.ToString();
                    p.CalculationRule = item.CalculationRule;
                    p.PunishmentRule = item.PunishmentRule;
                    p.CalculationRuleContent = rulelist.Where(info => info.Id == item.CalculationRule).FirstOrDefault()?.Content;
                    p.PunishmentRuleContent = rulelist.Where(info => info.Id == item.PunishmentRule).FirstOrDefault()?.Content;
                    //获取项目类别
                    var project = projectlist.Where(info => info.Id == item.ProjectId).ToList().FirstOrDefault();
                    if (project != null)
                    {
                        p.ProjectType = projecttypelist.Where(info => info.Id == project.ProjectTypeID).ToList().FirstOrDefault()?.Name;
                    }
                    list.Add(p);
                }
                res.TotalCount = count;
                res.Code = HttpResultCode.Success;
                res.Data = list;
                res.IsSuccess = true;
                res.Message = "查询成功";
            }
            else
            {
                res.IsSuccess = false;
                res.Code = HttpResultCode.NotData;
                res.Message = "未查询到数据";
                res.Data = null;
            }
            return res;
        }

        /// <summary>
        /// 根据赛事ID获取当前赛事状态为正在报名到比赛结束之前的赛事项目列表
        /// 用于添加报名时根据赛事ID获取
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetComProjectListByComIdDto>> GetComProjectListByComId(GetComProjectListByComIdQuery query)
        {
            var res = new ResultListDto<GetComProjectListByComIdDto>();
            var list = new List<GetComProjectListByComIdDto>();
            var projects = await repository.GetAllListAsync(a => a.CompetitionId == query.CompetitionId && a.IsDeleted == false && a.State > 1 && a.State < 6);
            if (projects.Count > 0)
            {
                foreach (var item in projects)
                {
                    var dto = new GetComProjectListByComIdDto();
                    dto.Id = item.Id;
                    dto.Name = item.Name;
                    list.Add(dto);
                }
                res.Data = list;
                res.Code = HttpResultCode.Success;
                res.Message = "获取成功";
                res.IsSuccess = true;
                res.Count = projects.Count;
            }
            else
            {
                res.Code = HttpResultCode.NotData;
                res.Message = "未查询到数据";
                res.IsSuccess = true;
                res.Count = 0;
            }

            return res;
        }

        /// <summary>
        /// 获取当前比赛项目列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetCurrentCompetitionProjectListDto>> GetCurrentCompetitionProjectList()
        {
            ResultListDto<GetCurrentCompetitionProjectListDto> resultListDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var _retlist = (await repository.GetAllListAsync(info => (info.State == (int)CompetitionProjectStateEnum.待分组 || info.State == (int)CompetitionProjectStateEnum.待签到 || info.State == (int)CompetitionProjectStateEnum.正在比赛) && info.IsDeleted == false))
                    .WhereIF(token.CompanyId != null, info => comRepository.FirstOrDefault(com => com.Id == info.CompetitionId).Merchants == token.CompanyId)
                    .OrderByDescending(info => info.GameBeginTime)
                    .ToList();
                if (_retlist != null && _retlist.Count > 0)
                {
                    var cominfolist = await comRepository.GetAllListAsync(info => info.IsEnable == (int)EnableAndDisableStateEnum.启用 && info.IsDeleted == false && info.State != (int)CompetitionStateEnum.关闭);
                    var reglist = await regRepository.GetAllListAsync(info => info.IsDeleted == false && info.RegistrationStatus == (int)RegistrationStatusEnum.报名成功);
                    var rulelist = await ruleRepository.GetAllListAsync();
                    var projectlist = await projectRepository.GetAllListAsync();
                    var projecttypelist = await typeRepository.GetAllListAsync();
                    var dtolist = new List<GetCurrentCompetitionProjectListDto>();
                    foreach (var item in _retlist)
                    {
                        var cominfo = cominfolist.Where(info => info.Id == item.CompetitionId).ToList().FirstOrDefault();
                        if (cominfo != null)
                        {
                            var dto = new GetCurrentCompetitionProjectListDto();
                            dto.Id = item.Id;
                            dto.Address = item.Address + " | " + item.Stadium;
                            dto.GameType = item.GameType;
                            dto.GameTypeName = Enum.GetName(typeof(CompetitionProjectTypeEnum), item.GameType);
                            var gameendtime = item.GameBeginTime.Date == item.GameEndTime.Date ? item.GameEndTime.ToString("HH:mm") : item.GameEndTime.ToString("yyyy-MM-dd HH:mm");
                            dto.GameDate = $"{item.GameBeginTime.ToString("yyyy-MM-dd HH:mm")} ～{gameendtime}";
                            dto.SensorsMaxNum = item.SensorsMaxNum;
                            dto.TeamMaxUserNum = item.TeamMaxUserNum;
                            dto.MaxEmployeeNum = item.MaxEmployeeNum;
                            dto.Name = item.Name;
                            dto.CompetitionId = cominfo.Id;
                            dto.CompetitionName = cominfo.Name;
                            dto.UserNum = reglist.Where(info => info.CompetitionProjectId == item.Id && info.CompetitionId == cominfo.Id).ToList().Count;
                            dto.State = item.State;
                            dto.Money = item.IsFree == true ? "0" : item.CostMoney.ToString();
                            dto.CalculationRule = item.CalculationRule;
                            dto.PunishmentRule = item.PunishmentRule;
                            dto.CalculationRuleContent = rulelist.Where(info => info.Id == item.CalculationRule).FirstOrDefault()?.Content;
                            dto.PunishmentRuleContent = rulelist.Where(info => info.Id == item.PunishmentRule).FirstOrDefault()?.Content;
                            //获取项目类别
                            var project = projectlist.Where(info => info.Id == item.ProjectId).ToList().FirstOrDefault();
                            if (project != null)
                            {
                                dto.ProjectType = projecttypelist.Where(info => info.Id == project.ProjectTypeID).ToList().FirstOrDefault()?.Name;
                            }
                            dtolist.Add(dto);
                        }
                    }
                    if (dtolist != null && dtolist.Count > 0)
                    {
                        resultListDto.IsSuccess = true;
                        resultListDto.Code = HttpResultCode.Success;
                        resultListDto.Message = "查询成功！";
                        resultListDto.Data = dtolist;
                        resultListDto.Count = dtolist.Count;
                    }
                    else
                    {
                        resultListDto.IsSuccess = false;
                        resultListDto.Code = HttpResultCode.NotData;
                        resultListDto.Message = "未查询到数据！";
                    }
                }
                else
                {
                    resultListDto.IsSuccess = false;
                    resultListDto.Code = HttpResultCode.NotData;
                    resultListDto.Message = "未查询到数据！";
                }

            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 新增、修改赛事比赛项目
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> EditCompetitionProjec(EditCompetitionProjecQuery query)
        {
            var res = new BaseResultDto();
            var pro = ObjectMapper.Map<CompetitionProject>(query);
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                if (query.Id == Guid.Empty || query.Id == null)
                {
                    pro.Id = Guid.NewGuid();
                    pro.CreateTime = DateTime.Now;
                    pro.CreateUserId = token.Id;

                    //成绩计算规则
                    await rapRepository.InsertAsync(new RuleApplyProject
                    {
                        CreateTime = DateTime.Now,
                        ProjectID = pro.ProjectId,
                        RuleID = pro.CalculationRule,
                        CreateUserId = token.Id,
                    });
                    //成绩惩罚规则
                    await rapRepository.InsertAsync(new RuleApplyProject
                    {
                        CreateTime = DateTime.Now,
                        ProjectID = pro.ProjectId,
                        RuleID = pro.PunishmentRule,
                        CreateUserId = token.Id,
                    });
                    var Id = await repository.InsertAndGetIdAsync(pro);
                    if (Id != Guid.Empty)
                    {
                        res.Code = HttpResultCode.Success;
                        res.Message = "保存成功";
                        res.IsSuccess = true;
                    }
                    else
                    {
                        res.Code = HttpResultCode.Error;
                        res.Message = "保存失败";
                        res.IsSuccess = false;
                    }
                }
                else
                {
                    pro = new CompetitionProject();
                    pro = repository.Get((Guid)query.Id);
                    pro.Address = query.Address;
                    pro.ProjectId = query.ProjectId;
                    pro.Name = query.Name;
                    pro.SensorsMaxNum = query.SensorsMaxNum;
                    pro.TeamMaxUserNum = query.TeamMaxUserNum;
                    pro.Stadium = query.Stadium;
                    pro.TelePhone = query.TelePhone;
                    pro.Consultant = query.Consultant;
                    pro.CalculationRule = query.CalculationRule;
                    pro.PunishmentRule = query.PunishmentRule;
                    pro.CostMoney = query.CostMoney;
                    pro.CostType = query.CostType;
                    pro.DetailsAddress = query.DetailsAddress;
                    pro.State = query.State;
                    pro.GameType = query.GameType;
                    pro.SignUpLimit = query.SignUpLimit;
                    pro.GroupLimit = query.GroupLimit;
                    pro.GameEndTime = query.GameEndTime;
                    pro.GameTime = query.GameTime;
                    pro.FinalsGameTime = query.FinalsGameTime;
                    pro.IsFree = query.IsFree;
                    pro.Point = query.Point;
                    //pro.GameDate = query.GameDate;
                    pro.GameBeginTime = query.GameBeginTime;
                    pro.UpdateTime = DateTime.Now;
                    pro.UpdateUserId = token.Id;
                    pro.MaxEmployeeNum = query.MaxEmployeeNum;
                    var project = await repository.UpdateAsync(pro);


                    var rules = await rapRepository.GetAllListAsync(r => r.ProjectID == pro.Id);

                    if (rules.Count > 0)
                    {
                        rules.ForEach(async r =>
                        {
                            var rule = await ruleRepository.GetAsync(r.RuleID);
                            rule.IsDeleted = true;
                            rule.DeleteTime = DateTime.Now;
                            rule.DeleteUserId = token.Id;
                            await ruleRepository.UpdateAsync(rule);
                        });
                    }
                    //成绩计算规则
                    await rapRepository.InsertAsync(new RuleApplyProject
                    {
                        CreateTime = DateTime.Now,
                        ProjectID = pro.ProjectId,
                        RuleID = pro.CalculationRule,
                        CreateUserId = token.Id,
                    });
                    //成绩惩罚规则
                    await rapRepository.InsertAsync(new RuleApplyProject
                    {
                        CreateTime = DateTime.Now,
                        ProjectID = pro.ProjectId,
                        RuleID = pro.PunishmentRule,
                        CreateUserId = token.Id,
                    });


                    if (project != null)
                    {
                        res.Code = HttpResultCode.Success;
                        res.Message = "保存成功";
                        res.IsSuccess = true;
                    }
                    else
                    {
                        res.Code = HttpResultCode.Error;
                        res.Message = "保存失败";
                        res.IsSuccess = false;
                    }
                }
            }
            catch (Exception ex)
            {
                res.Code = HttpResultCode.Error;
                res.Message = ex.Message;
                res.IsSuccess = false;
            }

            return res;
        }

        /// <summary>
        /// 结束报名
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> EndSignUp(CompetitionProjectIdQuery query)
        {
            var res = new BaseResultDto();
            var pro = await repository.GetAsync(query.Id);
            if (pro != null)
            {
                pro.State = (int)CompetitionProjectStateEnum.待分组;
                var project = await repository.UpdateAsync(pro);
                if (project != null)
                {
                    res.IsSuccess = true;
                    res.Code = HttpResultCode.Success;
                    res.Message = "操作成功";
                }
                else
                {
                    res.IsSuccess = false;
                    res.Code = HttpResultCode.Error;
                    res.Message = "操作失败";
                }
            }
            else
            {
                res.IsSuccess = false;
                res.Code = HttpResultCode.NotData;
                res.Message = "未查询到数据";
            }
            return res;
        }

        /// <summary>
        /// 结束赛事项目
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> EndCompetitionProject(CompetitionProjectIdQuery query)
        {
            var res = new BaseResultDto();
            var pro = await repository.GetAsync(query.Id);
            if (pro != null)
            {
                pro.State = (int)CompetitionProjectStateEnum.比赛结束;
                var project = await repository.UpdateAsync(pro);
                if (project != null)
                {
                    res.IsSuccess = true;
                    res.Code = HttpResultCode.Success;
                    res.Message = "操作成功";
                }
                else
                {
                    res.IsSuccess = false;
                    res.Code = HttpResultCode.Error;
                    res.Message = "操作失败";
                }
            }
            else
            {
                res.IsSuccess = false;
                res.Code = HttpResultCode.NotData;
                res.Message = "未查询到数据";
            }
            return res;
        }

        /// <summary>
        /// 启用比赛项目
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> EnableCompetitionProject(CompetitionProjectIdQuery query)
        {
            var res = new BaseResultDto();
            var pro = await repository.GetAsync(query.Id);
            if (pro != null)
            {
                pro.State = (int)CompetitionProjectStateEnum.待报名;
                var project = await repository.UpdateAsync(pro);
                if (project != null)
                {
                    res.IsSuccess = true;
                    res.Code = HttpResultCode.Success;
                    res.Message = "操作成功";
                }
                else
                {
                    res.IsSuccess = false;
                    res.Code = HttpResultCode.Error;
                    res.Message = "操作失败";
                }
            }
            else
            {
                res.IsSuccess = false;
                res.Code = HttpResultCode.NotData;
                res.Message = "未查询到数据";
            }
            return res;
        }

        /// <summary>
        /// 关闭比赛项目
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost, Route("CloseCompetitionProject")]
        public async Task<BaseResultDto> CloseCompetitionProject(CompetitionProjectIdQuery query)
        {
            var res = new BaseResultDto();
            var pro = await repository.GetAsync(query.Id);
            if (pro != null)
            {
                pro.State = (int)CompetitionProjectStateEnum.关闭;
                var project = await repository.UpdateAsync(pro);
                if (project != null)
                {
                    res.IsSuccess = true;
                    res.Code = HttpResultCode.Success;
                    res.Message = "操作成功";
                }
                else
                {
                    res.IsSuccess = false;
                    res.Code = HttpResultCode.Error;
                    res.Message = "操作失败";
                }
            }
            else
            {
                res.IsSuccess = false;
                res.Code = HttpResultCode.NotData;
                res.Message = "未查询到数据";
            }
            return res;
        }

        /// <summary>
        /// 根据比赛项目Id获取比赛项目详情
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetCompetitionPorjectDetailsDto>> GetCompetitionPorjectDetailsById(CompetitionProjectIdQuery query)
        {
            var res = new ResultDto<GetCompetitionPorjectDetailsDto>();
            var pro = await repository.GetAsync(query.Id);
            if (pro != null)
            {
                var dto = ObjectMapper.Map<GetCompetitionPorjectDetailsDto>(pro);
                var type = await projectRepository.GetAsync(dto.ProjectId);
                if (type != null)
                {
                    dto.ProjectTypeId = type.ProjectTypeID;
                }
                dto.CalculationRuleContent = (await ruleRepository.FirstOrDefaultAsync(info => info.Id == dto.CalculationRule))?.Content;
                dto.PunishmentRuleContent = (await ruleRepository.FirstOrDefaultAsync(info => info.Id == dto.PunishmentRule))?.Content;
                dto.CompetitionName = (await comRepository.FirstOrDefaultAsync(info => info.Id == dto.CompetitionId))?.Name;
                res.Data = dto;
                res.Code = HttpResultCode.Success;
                res.IsSuccess = true;
                res.Message = "查询成功";
            }
            else
            {
                res.Data = null;
                res.Code = HttpResultCode.NotData;
                res.IsSuccess = false;
                res.Message = "未查到数据";
            }

            return res;
        }

        /// <summary>
        /// 获取比赛规则
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetRuleListDto>> GetRuleList(GetRuleListQuery query)
        {
            var res = new ResultListDto<GetRuleListDto>();
            var list = new List<GetRuleListDto>();
            var rule = await ruleRepository.GetAllListAsync();
            var projects = await projectRepository.GetAllListAsync();
            rule = rule.Where(a => a.Type == query.type && a.IsDeleted == false && a.State == (int)EnableAndDisableStateEnum.启用).ToList();
            if (rule.Count > 0)
            {
                var project = await projectRepository.GetAsync(query.ProjectId);
                foreach (var item in rule)
                {
                    var dto = new GetRuleListDto();
                    dto.Content = item.Content;
                    dto.Id = item.Id;
                    dto.Name = item.Name;
                    dto.Type = item.Type;
                    var ruleApplyProjects = await rapRepository.GetAllListAsync(c => c.RuleID == item.Id);
                    var rap = ruleApplyProjects.Select(c => c.ProjectID).ToList();
                    var proList = projects.Where(c => rap.Contains(c.Id));
                    var str = "";
                    if (proList != null && proList.Any())
                    {
                        str = String.Join(",", proList.Select(c => c.Name).ToArray());
                    }
                    dto.ApplyProject = str;
                    list.Add(dto);
                }
                res.Data = list.Where(l => l.ApplyProject.Contains(project.Name)).ToList();
                res.Code = HttpResultCode.Success;
                res.IsSuccess = true;
                res.Message = "查询成功";
            }
            else
            {
                res.Data = null;
                res.Code = HttpResultCode.NotData;
                res.IsSuccess = false;
                res.Message = "未查到数据";
            }
            return res;
        }


        /// <summary>
        /// 获取比赛分组报名人员列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetGroupListDto>> GetGroupList(GetGroupListQuery query)
        {
            var res = new ResultListDto<GetGroupListDto>();
            try
            {
                var reglist = await regRepository.GetAllListAsync(a => a.CompetitionProjectId == query.Id && a.RegistrationStatus == (int)RegistrationStatusEnum.报名成功 && a.IsDeleted == false);
                if (reglist!=null && reglist.Count > 0)
                {
                    var projectinfo = await repository.FirstOrDefaultAsync(query.Id);
                    var ems = await employeeRepository.GetAllListAsync(e => e.IsDeleted == false);
                    if (projectinfo.GameType == (int)CompetitionProjectTypeEnum.个人赛)
                    {
                        var list = ObjectMapper.Map<List<GetGroupListDto>>(reglist);
                        foreach (var item in list)
                        {
                            var emp = ems.FirstOrDefault(info => info.IDNumber == item.CompeteIdNo && info.RealName == item.CompeteName);
                            item.EmployeeId = !emp.IsNullAndEmpty() ? emp.Id : Guid.Empty;
                            item.Sensor = item.SensorNumber;
                            item.CompeteTeamInfos = new();
                        }
                        res.Code = HttpResultCode.Success;
                        res.IsSuccess = true;
                        res.Data = list;
                        res.Count = list.Count;
                        res.Message = "查询成功";
                    }
                    else
                    {
                        var comteamlist = reglist.GroupBy(info => new { info.CompeteTeamId, info.CompeteTeamName }).Select(g => new { g.Key.CompeteTeamId, g.Key.CompeteTeamName }).ToList();
                        List<GetGroupListDto> listDtos = new();
                        foreach (var item in comteamlist)
                        {
                            GetGroupListDto dto = new();
                            dto.CompeteTeamId = item.CompeteTeamId;
                            dto.CompeteTeamName = item.CompeteTeamName;
                            var teamreglist = reglist.Where(info => info.CompeteTeamId == item.CompeteTeamId);
                            List<GroupCompeteTeamInfoDto> groupteamlist = new();
                            foreach (var teamreg in teamreglist)
                            {
                                GroupCompeteTeamInfoDto competeTeamInfo = new();
                                competeTeamInfo.CompeteTel = teamreg.CompeteTel;
                                competeTeamInfo.CompeteIdNo = teamreg.CompeteIdNo;
                                competeTeamInfo.Sensor=teamreg.SensorNumber;
                                competeTeamInfo.CompeteName = teamreg.CompeteName;
                                competeTeamInfo.CompeteTeamName = item.CompeteTeamName;
                                competeTeamInfo.EmployeeName= teamreg.CompeteName;
                                competeTeamInfo.EmployeeTel= teamreg.CompeteTel;
                                competeTeamInfo.EmployeeIdNo= teamreg.CompeteIdNo;
                                var empinfo = ems.FirstOrDefault(info => info.IDNumber == teamreg.CompeteIdNo && info.RealName == teamreg.CompeteName);
                                competeTeamInfo.EmployeeId = (Guid)empinfo?.Id;
                                groupteamlist.Add(competeTeamInfo);
                            }
                            dto.CompeteTeamInfos = groupteamlist;
                            listDtos.Add(dto);
                        }
                        res.Code = HttpResultCode.Success;
                        res.IsSuccess = true;
                        res.Data = listDtos;
                        res.Count = comteamlist.Count;
                        res.Message = "查询成功";

                    }
                }
                else
                {
                    res.Code = HttpResultCode.NotData;
                    res.IsSuccess = false;
                    res.Data = null;
                    res.Message = "未查到数据";
                }
            }
            catch (Exception e)
            {
                res.Code = HttpResultCode.Error;
                res.IsSuccess = false;
                res.Data = null;
                res.Message = e.Message.ToString();
            }
            return res;
        }


        /// <summary>
        /// 根据赛事项目ID获取最大报名人数限制和是否达到最大报名人数限制
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetMaxEmployeeNumDto>> GetMaxEmployeeNum([FromBody] GetMaxEmployeeNumQuery query)
        {
            ResultDto<GetMaxEmployeeNumDto> result = new ResultDto<GetMaxEmployeeNumDto>();
            GetMaxEmployeeNumDto dto = new GetMaxEmployeeNumDto();
            var project = await repository.GetAsync(query.CompetitionProjectId);
            if (project != null)
            {
                dto.MaxEmployeeNum = project.MaxEmployeeNum;
                //查询当前项目的报名人数
                var reg = await regRepository.GetAllListAsync(a => a.RegistrationStatus < 3 && a.CompetitionProjectId == query.CompetitionProjectId);
                if (reg.Count < project.MaxEmployeeNum)
                {
                    dto.IsFull = false;
                }
                else
                {
                    dto.IsFull = true;
                }
                result.IsSuccess = true;
                result.Data = dto;
                result.Code = HttpResultCode.Success;
                result.Message = "查询成功";
            }
            else
            {
                result.Code = HttpResultCode.NotData;
                result.IsSuccess = false;
                result.Message = "未查询到该赛事项目";
            }
            return result;
        }

        /// <summary>
        /// 客户端分页获取赛事项目信息（用于信息同步）
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetPageCompetitionPorjectKHDDto>> GetPageCompetitionPorjectKHD(BasePageQuery query)
        {
            PagePagingDto<GetPageCompetitionPorjectKHDDto> pagingDto = new();
            try {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                var comlist = (await comRepository.GetAllListAsync())
                               .WhereIF(token.CompanyId != null, info => info.Merchants == token.CompanyId).ToList();
                var retlist = (await repository.GetAllListAsync(info => info.IsDeleted == false))
                         .WhereIF(token.CompanyId != null, info => comlist.FirstOrDefault(com => com.Id == info.CompetitionId) != null)
                         .ToList();
                var pageretlist = retlist.Skip(query.PageSize * (query.PageIndex - 1))
                .Take(query.PageSize).ToList();
                if (pageretlist != null && pageretlist.Count() > 0)
                {
                    pagingDto.IsSuccess = true;
                    pagingDto.Code = HttpResultCode.Success;
                    pagingDto.Message = "查询成功！";
                    pagingDto.Data = ObjectMapper.Map<List<GetPageCompetitionPorjectKHDDto>>(pageretlist);
                    pagingDto.TotalCount = retlist.Count;
                }
                else {
                    pagingDto.IsSuccess = true;
                    pagingDto.Code = HttpResultCode.NotData;
                    pagingDto.Message = "未查询到数据!";
                }
            } catch (Exception ex) {
                pagingDto.IsSuccess = false;
                pagingDto.Code = HttpResultCode.Error;
                pagingDto.Message = ex.Message.ToString();
            }
            return pagingDto;
        }

        /// <summary>
        /// 客户端赛事项目信息同步
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> CompetitionPorjectSynchronization(List<CompetitionPorjectSynchronizationQuery> query)
        {
            BaseResultDto baseResultDto = new();
            try
            {
                foreach (var item in query)
                {
                    var comporjectinfo = ObjectMapper.Map<CompetitionProject>(item);
                    await repository.InsertOrUpdateAsync(comporjectinfo);
                }
                baseResultDto.IsSuccess = true;
                baseResultDto.Code = HttpResultCode.Success;
                baseResultDto.Message = "同步成功！";

            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
        #endregion
    }
}
